﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Entities;
using Volo.Abp;
using XfTech.SmartTms.Enums;
using XfTech.SmartTms.Exceptions;
using Volo.Abp.Auditing;
using XfTech.SmartTms.Specifications;
using System.Runtime.InteropServices;

namespace XfTech.SmartTms.Entities.Issues
{
    /// <summary>
    /// 问题Issue 实体模型（聚合根）
    /// </summary>
    public class Issue : AggregateRoot<Guid>, IHasCreationTime
    {
        /// <summary>
        /// 仓库Id
        /// </summary>
        public Guid RepositoryId { get; private set; }

        /// <summary>
        /// 问题标题
        /// </summary>
        public string Title { get; private set; }

        /// <summary>
        /// 问题内容
        /// </summary>
        public string Text { get; set; }

        /// <summary>
        /// 负责人Id
        /// </summary>
        public Guid? AssignedUserId { get; internal set; }

        /// <summary>
        /// 是否关闭
        /// </summary>
        public bool IsClosed { get; private set; }

        /// <summary>
        /// 是否被锁
        /// </summary>
        public bool IsLocked { get; private set; }

        /// <summary>
        /// 关闭理由
        /// </summary>
        public IssueCloseReason? CloseReason { get; private set; } //enum

        /// <summary>
        /// 标签
        /// </summary>
        public ICollection<IssueLabel> Labels { get; set; }

        public DateTime CreationTime { get; private set; }

        public DateTime? LastCommentTime { get; private set; }

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="id"></param>
        /// <param name="repositoryId"></param>
        /// <param name="title"></param>
        /// <param name="text"></param>
        /// <param name="assignedUserId"></param>
        public Issue(
            Guid id,
            Guid repositoryId,
            string title,
            string text = null,
            Guid? assignedUserId = null
            ) : base(id)
        {
            RepositoryId = repositoryId;
            Title = Check.NotNullOrWhiteSpace(title, nameof(title));

            Text = text;
            AssignedUserId = assignedUserId;

            IsClosed = false;
            IsLocked = false;

            CreationTime = DateTime.Now; //创建时间为当前

            Labels = new Collection<IssueLabel>();
        }

        /// <summary>
        /// 无参构造方法 仅仅用作ORM反序列化
        /// </summary>
        private Issue() { /* for deserialization & ORMs */ }

        /// <summary>
        /// 修改标题
        /// </summary>
        /// <param name="title"></param>
        public void SetTitle(string title)
        {
            Title = Check.NotNullOrWhiteSpace(title, nameof(title));
        }

        /// <summary>
        /// 设置标签
        /// </summary>
        /// <param name="labels"></param>
        public void SetLabels(List<Guid> labels)
        {
            //添加 问题标签关系数据
            labels?.ForEach(labelId => {
                IssueLabel issueLabel = new IssueLabel(this.Id, labelId);

                //添加到 问题标签集合中
                this.Labels.Add(issueLabel);
            });
        }

        /// <summary>
        /// 关闭问题
        /// </summary>
        /// <param name="reason"></param>
        public void Close(IssueCloseReason reason)
        {
            IsClosed = true;
            CloseReason = reason;
        }

        /// <summary>
        /// 重新打开问题
        /// </summary>
        public void ReOpen()
        {
            if (IsLocked)
            {
                throw new BusinessException("IssueTracking:CanNotOpenLockedIssue");
            }

            IsClosed = false;
            CloseReason = null;
        }

        /// <summary>
        /// 锁定
        /// </summary>
        public void Lock()
        {
            if (!IsClosed)
            {
                throw new BusinessException("IssueTracking:CanNotLockOpenedIssue");
            }

            IsLocked = true;
        }

        /// <summary>
        /// 解锁
        /// </summary>
        public void Unlock()
        {
            IsLocked = false;
        }

        /// <summary>
        /// 分配负责人
        /// </summary>
        /// <param name="user"></param>
        /// <param name="userIssueService"></param>
        /// <returns></returns>
        /// <exception cref="BusinessException"></exception>
        //public async Task AssignToAsync(AppUser user, IUserIssueService userIssueService)
        //{
        //    var openIssueCount = await userIssueService.GetOpenIssueCountAsync(user.Id);

        //    if (openIssueCount >= 3)
        //    {
        //        throw new BusinessException("IssueTracking:ConcurrentOpenIssueLimit");
        //    }

        //    AssignedUserId = user.Id;
        //}

        /// <summary>
        /// 清除负责人
        /// </summary>
        public void CleanAssignment()
        {
            AssignedUserId = null;
        }

        /// <summary>
        /// 判断是否活跃
        /// </summary>
        /// <returns></returns>
        public bool IsInActive()
        {
            return new InActiveIssueSpecification().IsSatisfiedBy(this);
        }
    }
}
